package worker

import (
	"context"
	"errors"
	"fmt"
	"time"

	"zhonghui/console/service"
	"zhonghui/console/warehouse/dbx"
	"zhonghui/console/warehouse/dbx/cache_main"
	"zhonghui/console/warehouse/dbx/db_zh_kernel"
	"zhonghui/console/warehouse/dbx/db_zh_kernel_slave"
	"zhonghui/console/warehouse/helperx"
	"zhonghui/console/warehouse/logx"
	"zhonghui/console/warehouse/modelx/model_zh_kernel"
)

// UserPropWorker 检测并解析用户画像，如地区、设备等
type UserPropWorker struct {
}

func (w *UserPropWorker) Start() {
	w.do()
	t := time.NewTicker(1 * time.Minute)
	for {
		select {
		case <-t.C:
			w.do()
		}
	}
}

func (w *UserPropWorker) do() {
	defer func() {
		if r := recover(); r != nil {
			logx.Zap().Errorw("定时任务异常", "err", errors.New(fmt.Sprintf("%s", r)))
		}
	}()

	rc := cache_main.Client()
	lock, ch, err := dbx.GetRedisLockWithRefresh(rc, dbx.RedisPrefix("locker-UserPropWorker"), 5*time.Second, time.Second)
	if err != nil {
		return
	}
	defer func() {
		if ch != nil {
			ch <- 1
		}
		_ = lock.Release(context.Background())
	}()

	// 查询进行中的任务，和暂停的任务
	list := make([]model_zh_kernel.SysSmsRecord, 0)
	db_zh_kernel_slave.Client().
		Where("ip != '' and area = '' and device = '' and update_time < ?", time.Now().Add(-3*time.Minute).Format(helperx.TimeLayoutCommon)).
		Limit(100).
		Find(&list)

	for _, item := range list {
		loc := service.GetLocFromIP(item.Ip)
		area := loc.Province
		if area == "" {
			area = "未知"
		}

		ua := service.GetUAFromString(item.Ua)
		device := fmt.Sprintf("%s-%s-%s", ua.OS, ua.Device, ua.Name)
		if device == "" {
			device = "未知"
		}

		db_zh_kernel.Client().Exec("update sys_sms_record set area = ?, device = ? where id = ?", area, device, item.ID)
	}
}
